package cn.ytr.project.web.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.ytr.project.domain.AdminUser;
import cn.ytr.project.service.IAdminUserService;
import cn.ytr.project.service.impl.AdminUserServiceImpl;
import cn.ytr.project.util.FileUploadUtils;
import cn.ytr.project.util.StringUtil;

@WebServlet("/adminUser")
public class AdminUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private IAdminUserService service = new AdminUserServiceImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		
		String cmd = req.getParameter("cmd");
		if ("login".equals(cmd)) {
			login(req, resp);
		} else if ("logout".equals(cmd)) {
			logout(req, resp);
		} else if ("registerTo".equals(cmd)) {
			try {
				registerTo(req, resp);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		} else if ("saveOrUpate".equals(cmd)) {
			saveOrUpate(req, resp);
			
		} else if ("register".equals(cmd)) {
			register(req, resp);
			
		} else {
			list(req, resp);
		}
		
	}
	
	/**
	 * 显示用户注册页 register.jsp
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String name = req.getParameter("name");
		if (StringUtil.hasLength(name)) {
			AdminUser adminUser = service.selectByUsername(name);
			req.setAttribute("user", adminUser);
		}
		req.getRequestDispatcher("/adminUserInput.jsp").forward(req, resp);
	}
	

	/**
	 * 显示用户列表页
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<AdminUser> list = service.selectForList();
		req.setAttribute("users", list);
		req.getRequestDispatcher("/WEB-INF/views/adminUserList.jsp").forward(req, resp);
	}
	
	/**
	 * 用户注册页面 提交表单时：上传图片
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 * @throws FileUploadException 
	 */
	protected void registerTo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, FileUploadException {
		String username = null;
		String password = null;
		String id = null;
		
		//获取参数
		// 创建创建FileItem对象的工厂
		FileItemFactory factory = new DiskFileItemFactory();
		// 创建文件上传处理器
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 解析请求,得到一个一个的FileItem对象(FileItem对象--->一个表单元素)
		//设置上传文件的大小
		upload.setFileSizeMax(1024*1024*2);
		List<FileItem> items = upload.parseRequest(req);
		for (FileItem fileItem : items) {
			if ("username".equals(fileItem.getFieldName())) {
				username = fileItem.getString("utf-8");
			} else if ("password".equals(fileItem.getFieldName())) {
				password = fileItem.getString("utf-8");
			} else if ("id".equals(fileItem.getFieldName())) {
				id = fileItem.getString();
			}
		}
		
		AdminUser userOld = service.selectByUsername(username);
		//判断数据是否有值以及判断用户名有没有被注册
		if ( !StringUtil.hasLength(username) || !StringUtil.hasLength(password) ) {
			req.setAttribute("errorMessage", "用户名和密码不允许为空");
			req.getRequestDispatcher("/adminUserInput.jsp").forward(req, resp);
			return;
		} else {
			if (!StringUtil.hasLength(id)) {
				if (userOld != null) {
					req.setAttribute("errorMessage", "该用户名已存在！");
					req.getRequestDispatcher("/adminUserInput.jsp").forward(req, resp);
					return;
				}
			}
		}
		
		
		// 判断请求是否满足文件上传的要求(请求方式为post/数据的编码方式multipart/form-data)
		boolean multipartContent = ServletFileUpload.isMultipartContent(req);
		// 如果满足要求,执行文件上传
		if (multipartContent) {
			//调用上传文件的工具类
			Map<String, Object> map = FileUploadUtils.upload(req, items);
			
			AdminUser adminUser = new AdminUser();
			// 将map中的数据转换成 User 对象
			try {
				adminUser.setUsername(map.get("username").toString());
				adminUser.setPassword(map.get("password").toString());
				if (map.get("imgPath") != null) {
					adminUser.setImgPath(map.get("imgPath").toString());
				} else {
					if (userOld != null) {
						adminUser.setImgPath(userOld.getImgPath());
					}
				}
				adminUser.setCreateDate(new Date());
				adminUser.setId(Long.valueOf(map.get("id").toString()));
			} catch (Exception e) {
				e.printStackTrace();
			} 

			if (adminUser.getId() == null || !StringUtil.hasLength(adminUser.getId().toString())) {
				service.insert(adminUser);
			} else {
				service.update(adminUser);
			}
			
			resp.sendRedirect("/adminUser");
			return;
		}
		
		resp.sendRedirect("/adminUser");
	}
	
	protected void saveOrUpate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
	}

	/**
	 * 登录页面提交后的处理方法
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String rememberMe = req.getParameter("rememberMe");
		
		//先验证验证码
		String userCode = req.getParameter("randomCode");
		String sessionCode = (String) req.getSession().getAttribute("RANDOMCODE_IN_SESSION");
		if(StringUtil.hasLength(userCode) && StringUtil.hasLength(sessionCode)){
			if(!userCode.equals(sessionCode)){
				req.setAttribute("errorMessage", "亲,验证码不正确");
				req.getRequestDispatcher("/login.jsp").forward(req, resp);
				return;
			}
		}else{
			req.setAttribute("errorMessage", "亲,验证码为空或者以失效");
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
			return;
		}
		
		if (StringUtil.hasLength(username) && StringUtil.hasLength(password)) {
			AdminUser adminUser = service.selectByUsernameAndPassword(username, password);
			if (adminUser != null) {
				
				HttpSession session = req.getSession();
				session.setAttribute("USER_IN_SESSION", adminUser);
				
				//记住我
				if (StringUtil.hasLength(rememberMe)) {
					Cookie usernameCookie = new Cookie("username", username);
					Cookie passwordCookie = new Cookie("password", password);
					Cookie rememberMeCookie = new Cookie("rememberMe", rememberMe);
					resp.addCookie(usernameCookie);
					resp.addCookie(passwordCookie);
					resp.addCookie(rememberMeCookie);
				} else {
					Cookie[] cs = req.getCookies();
					for (Cookie cookie : cs) {
						if (cookie.getName().equals("username") || cookie.getName().equals("password")
								|| cookie.getName().equals("rememberMe") ) {
							cookie.setMaxAge(0);
							resp.addCookie(cookie);
						}
					}
				}
				
				resp.sendRedirect("/product");
			} else {
				req.setAttribute("errorMessage", "用户名或密码不匹配");
				req.getRequestDispatcher("/login.jsp").forward(req, resp);
			}
		} else {
			req.setAttribute("errorMessage", "用户名或密码不可为空");
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
		}
	}
	
	/**
	 * 退出登录
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpSession session = req.getSession();
		session.removeAttribute("USER_IN_SESSION");
		resp.sendRedirect("/login.jsp");
	}
	

}
